package com.module.login.view

import android.content.Intent
import android.text.TextUtils
import android.view.View
import com.module.app.base.BaseActivity
import com.module.app.ext.loginFlow
import com.module.base.ext.countDownByFlow
import com.module.base.utils.StatusMyBarUtil
import com.module.base.utils.ToastUtils
import com.module.frame.ext.observe
import com.module.login.bean.ILoginType
import com.module.login.databinding.LoginActivityLoginCodeBinding
import com.module.login.model.LoginCodeViewModel
import com.module.login.utils.EXTRA_PHONE

class LoginCodeActivity : BaseActivity<LoginCodeViewModel, LoginActivityLoginCodeBinding>() {
    private val phone: String by lazy {
        intent.getStringExtra(EXTRA_PHONE).toString()
    }

    override fun bingViewModel() {
        mDatabind.vm = mViewModel
    }

    override fun initView() {
        super.initView()
        StatusMyBarUtil.setPaddingSmart(getContext(), mDatabind.ivBack)
        mDatabind.tvPhone.text = phone
    }

    override fun initListener() {
        super.initListener()
        //登录监听
        observe(loginFlow) {
            if (it) {
                loginSuc()
            }
        }
        mDatabind.etCode.setOnPinEnteredListener { str ->
            mViewModel.verifyCode(
                phone,
                str.toString()
            )
        }
        observe(mViewModel.sendCodeFlow) {
            if (it) {
                sendCodeSuc()
            }
        }
        observe(mViewModel.verifyCodeFlow) {
            if (it) {
                verifyCodeSuc()
            } else {
                verifyCodeFail()
            }
        }
    }

    override fun initData() {
        super.initData()
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort("电话号码不能为空")
            finish()
            return
        }
        mViewModel.sendCode(phone)
    }

    fun sendCodeSuc() {
        mDatabind.tvSend.isEnabled = false
        countDownByFlow(59,
            {
                mDatabind.tvSend.text = "${it.toString()}s后重新获取验证码"
            }, {
                mDatabind.tvSend.text = "重新获取"
                mDatabind.tvSend.isEnabled = true
            })
    }

    private fun verifyCodeSuc() {
        mViewModel.login(phone)
    }

    private fun verifyCodeFail() {
        mDatabind.etCode.text = null
    }

    fun loginSuc() {
        val intent = Intent()
        setResult(ILoginType.IActivityCode.RESULT_LOGIN_CODE, intent)
        finish()
    }


    fun onClickBack(view: View) {
        finish()
    }

    fun onClickSend(view: View) {
        mViewModel.sendCode(phone)
    }


}